<template>
  <div class="app-container" v-loading="loading" style="width: 100%;">
    <el-row :gutter="20">
      <el-col
        :xs="24"
        :sm="24"
        :md="8"
        :lg="6"
        :xl="6"
        style="margin-bottom: 10px"
      >
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <div>
            <div style="text-align: center">
              <div class="el-upload">
                <img
                  :src="user.avatar ? spliceUrl(user.avatar) : Avatar"
                  title="点击上传头像"
                  class="avatar"
                  @click="toggleShow"
                />
                <myUpload
                  ref="myUpload"
                  v-model="show"
                  :headers="headers"
                  field="avatar"
                  :url="spliceUrl('/uploadAvatar')"
                  @crop-upload-success="cropUploadSuccess"
                />
              </div>
            </div>
            <ul class="user-info">
              <li>
                <div style="height: 100%">
                  <svg-icon icon-class="login" /> 登录账号
                  <div class="user-right">
                    {{ user.username ? user.username : "未填写" }}
                  </div>
                </div>
              </li>
              <li>
                <svg-icon icon-class="user1" /> 用户昵称
                <div class="user-right">
                  {{ user.nickName ? user.nickName : "未填写" }}
                </div>
              </li>
              <li>
                <svg-icon icon-class="phone" /> 手机号码
                <div class="user-right">
                  {{ user.phone ? user.phone : "未填写" }}
                </div>
              </li>
              <li>
                <svg-icon icon-class="email" /> 用户邮箱
                <div class="user-right">
                  {{ user.email ? user.email : "未填写" }}
                </div>
              </li>
              <li>
                <svg-icon icon-class="anq" /> 安全设置
                <div class="user-right">
                  <a @click="$refs.pass.dialog = true">修改密码</a>
                  <!-- <a @click="$refs.email.dialog = true">修改邮箱</a> -->
                </div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="16" :lg="18" :xl="18">
        <!--    用户资料    -->
        <el-card class="box-card">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="用户资料" name="first">
              <el-form
                ref="form"
                :model="form"
                :rules="rules"
                style="margin-top: 10px;"
                size="small"
                label-width="65px"
              >
                <el-form-item label="昵称" prop="nickName">
                  <el-input
                    v-model="form.nickName"
                    style="width: 35%"
                    placeholder="输入昵称"
                  />
                  <span style="color: #C0C0C0;margin-left: 10px;"
                    >用户昵称不作为登录使用</span
                  >
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input
                    v-model="form.phone"
                    style="width: 35%;"
                    placeholder="输入手机号码"
                  />
                  <span style="color: #C0C0C0;margin-left: 10px;"
                    >手机号码不能重复</span
                  >
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input
                    v-model="form.email"
                    style="width: 35%;"
                    placeholder="输入邮箱"
                    :disabled="true"
                  />
                  <a
                    style="color: #317ef3; margin-left: 10px;"
                    @click="$refs.email.dialog = true"
                    >修改邮箱</a
                  >
                </el-form-item>
                <el-form-item label="性别">
                  <el-radio-group v-model="form.gender" style="width: 178px">
                    <el-radio label="1">男</el-radio>
                    <el-radio label="0">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="权限">
                  <el-select
                    :disabled="bool"
                    v-model="permissions"
                    filterable
                    placeholder="请选择"
                    @change="change"
                  >
                    <el-option
                      v-for="item in rolesList"
                      :key="item.id"
                      :label="item.roleName"
                      :value="item.id"
                      :disabled="item.disabled === 1 ? false : true"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="">
                  <el-button
                    :loading="saveLoading"
                    size="mini"
                    type="primary"
                    @click="doSubmit"
                    >保存配置</el-button
                  >
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <!-- <el-tab-pane label="操作日志" name="second"> </el-tab-pane> -->
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
    <updatePass ref="pass" :userId="userId" />
    <!-- :getUserInfo="getUserInfo" -->
    <updateEmail ref="email" :email="String(form.email)"  />
  </div>
</template>
<script>
import { mapState, mapMutations, mapActions, mapGetters } from "vuex";
import { getToken } from "@/utils/auth";
import myUpload from "vue-image-crop-upload/upload-2.vue";
import updatePass from "@/components/tools/updatePass";
import updateEmail from "@/components/tools/updateEmail";
import Avatar from "@/assets/def_images/avatar.png";
import { validPhone } from "@/utils/validate";
export default {
  name:"Profile",
  components: {
    myUpload,
    updatePass,
    updateEmail
  },
  data() {
    // 自定义验证
    const isvalidPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入电话号码"));
      } else if (!validPhone(value)) {
        callback(new Error("请输入正确的11位手机号码"));
      } else {
        callback();
      }
    };
    return {
      show: false,
      headers: {
        "Admin-Token": getToken(),
        // "Content-Type": "multipart/form-data",
      },
      loading: true,
      activeName: "first",
      Avatar: Avatar,
      saveLoading: false,
      form: {},
      rules: {
        nickName: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        phone: [{ required: true, trigger: "blur", validator: isvalidPhone }]
      },
      rolesList: [],
      permissions: "",
      bool: false
    };
  },
  methods: {
    // 打开上传组件
    toggleShow() {
      this.show = !this.show;
    },

    // 上传组件
    cropUploadSuccess(jsonData, Field) {
      // console.log(Field); // 上传的表单字段名name
      // console.log(jsonData); // 上传成功返回的res数据）
      const Data = jsonData.data.file;
      let TempPath = Data.path.substr(
        Data.path.indexOf("avatars") - 1,
        Data.path.length
      ); // 截取路径
      this.updateAvatar({
        id: this.userId,
        avatarPath: TempPath.replace(/[\\]/g, "/") // 把路径 反斜杠"\" 转 正斜杠"/"
      }).then(res => {
        this.$message({
          message: res.msg,
          type: "success"
        });
        this.getUserInfo();
        setTimeout(() => {
          this.$refs.myUpload.setStep(1); // 返回上传组件第一步
          this.show = false; // 关闭弹窗
        }, 1000);
      });
    },
    ...mapActions("admin", ["checkRole"]),
    ...mapActions("user", ["getInfo", "updateUser", "updateAvatar"]),
    ...mapActions("role", ["getRole", "getRoleList"]),
    async getUserInfo() {
      this.loading = true;
      await this.getInfo({ userId: this.userId }).then(
        res => {
          this.form = {
            id: res.data.userInfo.id,
            username: res.data.userInfo.username,
            avatar: res.data.userInfo.avatar,
            nickName: res.data.userInfo.nickName,
            gender: res.data.userInfo.gender,
            phone: res.data.userInfo.phone,
            email: res.data.userInfo.email,
            roleId: res.data.userInfo.roleId
          };
          this.getRoles(this.form.roleId);
        }
      );
    },

    // 权限id获取用户权限
    async getRoles(id) {
      await this.getRole({ roleId: id }).then(res => {
        if (res.data.role.id === 0) {
          this.bool = true;
          this.permissions = res.data.role.roleName;
          this.loading = false;
        } else {
          this.permissions = res.data.role.roleName;
          this.getRolesList();
        }
      });
    },

    // 获取权限列表
    async getRolesList() {
      await this.getRoleList().then(res => {
        this.rolesList = res.data.rolesList;
        this.loading = false;
      });
    },

    // 选择权限
    change(e) {
      this.form.roleId = e;
    },

    handleClick(tab, event) {
      // console.log(tab);
      // if (tab.name === 'second') {
      //   this.init()
      // }
    },
    async updateCheckRole() {
      await this.checkRole();
    },

    // 提交个人信息
    doSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.updateUser(this.form).then(res => {
            this.$message({
              message: res.msg,
              type: "success"
            });
            this.getUserInfo();
            this.updateCheckRole();
          });
        }
      });
    }
  },
  created() {
    this.getUserInfo();
  },
  computed: {
    ...mapGetters(["user","userId"])
  }
};
</script>
<style lang="scss" scoped>
.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
}
.user-info {
  padding-left: 0;
  list-style: none;
  li {
    border-bottom: 1px solid #f0f3f4;
    padding: 11px 0;
    font-size: 13px;
  }
  .user-right {
    float: right;
    a {
      color: #317ef3;
    }
  }
}
</style>
